package com.gxd.base.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.gxd.base.entity.*;
import com.gxd.base.utils.ConverMapToObject;
import com.gxd.base.utils.JedisTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gxd.base.service.ManagerService;
import com.gxd.base.utils.MD5;

@CrossOrigin
@RestController
@RequestMapping("/manager")
public class ManagerController {

	@Autowired
	private ManagerService managerService;
	
	// 登陆
	@RequestMapping("/login")
	public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user){
		String userCode = user.getUserCode();
		String userPwd = user.getUserPassword();
		Map<String, Object> rsMap = managerService.login(userCode, userPwd);
		Date now = new Date();
		if(rsMap.containsKey("userInfo")){
			User userInfo = (User) rsMap.get("userInfo");
			request.getSession().setAttribute("userInfo", userInfo);
			// 获取用户权限及角色
			Map<String, Object> userRoleAndFun = managerService.getUserFunAndRole(userInfo.getUserId());
			rsMap.put("userRoleAndFun", userRoleAndFun);
			if(userCode.equals("liupx")){
				rsMap.put("isMap", "1");
			}else{
				rsMap.put("isMap", "0");
			}
			request.getSession().setAttribute("userRoleAndFun", userRoleAndFun);
			// 登陆成功后，将工号以MD5加密的方式，写入cookie
			String salt = MD5.passwordEncrypt(user.getUserCode()+now.getTime());
			JedisTool jedis = new JedisTool();
			JSONObject json = new JSONObject();
			List<Function> userFuns = (List<Function>)userRoleAndFun.get("funs");
			String permission = "";
			for(int i=0;i<userFuns.size();i++){
				if(i==(userFuns.size()-1)){
					permission += userFuns.get(i).getFunctionId();
				}else{
					permission = permission+userFuns.get(i).getFunctionId()+"-";
				}
			}
			json.put("userCode",user.getUserCode());
			json.put("userPermission",permission);
			jedis.set(salt,json.toJSONString());
			jedis.expire(salt,30*60);
			Cookie userCookie = new Cookie("salt", salt);
			userCookie.setMaxAge(30*60);
			userCookie.setPath("/");
			 response.addCookie(userCookie);
		}else{
			response.addCookie(new Cookie("salt", ""));
		}
		return rsMap;
	}
	// 根据工号，冻结账号：0未冻结   1已冻结
	@RequestMapping("/updateUserState")
	public Map<String, Object> updateUserState(@RequestBody Map<String, Object> paramMap){
		String userCode = paramMap.get("userCode")==null?"":paramMap.get("userCode").toString();
		return managerService.updateUserState(userCode);
	}
	// 新增用户
	@RequestMapping("/addUser")
	public Map<String, Object> addUser(@RequestBody User user){
		return managerService.addUser(user);
	}
	// 新增部门
	@RequestMapping("/addOrganization")
	public Map<String, Object> addOrganization(@RequestBody Organization org){
		return managerService.addOrganization(org);
	}
	// 添加角色
	@RequestMapping("/addRole")
	public Map<String, Object> addRole(HttpServletRequest request, @RequestBody Role role){
		return managerService.addRole(request, role);
	}
	// 添加权限
	@RequestMapping("/addFunction")
	public Map<String, Object> addFunction(HttpServletRequest request, @RequestBody Function fun){
		return managerService.addFunction(request, fun);
	}
	// 修改密码
	@RequestMapping("/changePassword")
	public Map<String, Object> changePassword(@RequestBody User user){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User userInfo = managerService.getUserByCode(user.getUserCode());
		// 校验密码是否正确
		try {
			String userPwdMD5 = MD5.passwordEncrypt(user.getUserPassword());
			if(userPwdMD5.equals(userInfo.getUserPassword())){
				user.setUserPassword(user.getNewUserPassword());
				user.setModifyDate(new Date());
				managerService.updateUserPwd(user);
				resultMap.put("code", 1);
				resultMap.put("msg", "密码修改成功");
			}else{
				resultMap.put("code", 3);
				resultMap.put("msg", "工号或密码错误");
			}
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	// 修改用户信息
	@RequestMapping("/updateUser")
	public Map<String, Object> updateUser(@RequestBody User user){
		return managerService.updateUser(user);
	}
	// 修改部门
	@RequestMapping("/updateOrganization")
	public Map<String, Object> updateOrganization(@RequestBody Organization org){
		return managerService.updateOrganization(org);
	}
	// 修改权限记录
	@RequestMapping("/updateFunction")
	public Map<String, Object> updateFunction(@RequestBody Function fun, HttpServletRequest request){
		return managerService.updateFunction(request, fun);
	}
	// 修改角色（修改角色中的权限）
	@RequestMapping("/updateRoleFun")
	public Map<String, Object> updateRoleFun(@RequestBody Role role, HttpServletRequest request){
		String funArray = request.getParameter("funArray")==null?"":request.getParameter("funArray");
		return managerService.updateRoleFun(role, funArray);
	}
	// 修改权限状态
	@RequestMapping("/updateFunState")
	public Map<String, Object> updateFunState(@RequestBody Function fun){
		return managerService.updateFunState(fun);
	}
	// 根据角色ID，修改角色状态
	@RequestMapping("/updateRoleState")
	public Map<String, Object> updateRoleState(@RequestBody Role role){
		return managerService.updateRoleState(role.getRoleId());
	}
	// 获取权限类型
	@RequestMapping("/getDicList")
	public List<Dictionaries> getDicList(){
		return managerService.getDicList();
	}
	// 根据权限类型ID，获取类型记录
	@RequestMapping("/getDicById")
	public Dictionaries getDicById(@RequestBody Dictionaries dic){
		return managerService.getDicById(dic.getDicId());
	}
	// 根据工号，获取用户
	@RequestMapping("/getUserByCode")
	public User getUserByCode(@RequestBody Map<String, Object> paramMap){
		String userCode = paramMap.get("userCode")==null?"":paramMap.get("userCode").toString();
		User userInfo =  managerService.getUserByCode(userCode);
		userInfo.setUserPassword("");
		return userInfo;
	}
	// 获取权限列表
	@RequestMapping("/getFunctionList")
	public Page getFunctionList(@RequestBody Map<String, Object> paramMap){
		return managerService.getFunctionList(paramMap);
	}
	// 获取全部用户
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUserList")
	public Page getUserList(@RequestBody Map<String, Object> paramMap){
		Map<String, Object> rsMap = managerService.getUserList(paramMap);
		List<User> userList = (List<User>) rsMap.get("list");
		List<Map<String, Object>> mapUserList = new ArrayList<Map<String,Object>>();
		Page page = (Page) rsMap.get("page");
		for(User u : userList){
			Map<String, Object> uMap = (Map<String, Object>) ConverMapToObject.objectToMap(u);
			mapUserList.add(uMap);
		}
		page.setList(mapUserList);
		return page;
	}
	// 获取所有单位
	@RequestMapping("/getOrganizationList")
	public List<Organization> getOrganizationList(@RequestBody Organization org){
		return managerService.getOrganizationList(org);
	}
	// 获取所有单位(树形)
	@RequestMapping("/getOrganizationTree")
	public Organization getOrganizationTree(){
		return managerService.getOrganizationTree();
	}
	// 获取所有地区(树形)
	@RequestMapping("/getAreaTree")
	public Area getAreaTree(){
		return managerService.getAreaTree();
	}
	// 根据权限，获取菜单（树形）
	@RequestMapping("/getMenuTreeByFun")
	public Menu getMenuTreeByFun(@RequestBody Function fun){
		return managerService.getMenuTree(fun);
	}
	// 根据部门ID，获取部门详情
	@RequestMapping("/getOrgById")
	public Organization getOrgById(@RequestBody Organization org){
		return managerService.getOrgById(org.getOrgId());
	}
	// 获取所有角色
	@RequestMapping("/getRoleList")
	public List<Role> getRoleList(@RequestBody Role role){
		return managerService.getRoleList(role);
	}
	// 根据角色，获取权限列表
	@RequestMapping("/getFunListByRole")
	public List<Function> getFunctionList(Function function, @RequestBody Role role){
		return managerService.getFunctionListByRole(function, role);
	}
	// 根据用户，获取权限列表
	@RequestMapping("/getFunListByUser")
	public List<Function> getFunctionList(Function function, @RequestBody User user){
		return managerService.getFunListByUserId(function, user);
	}
	// 根据用户，获取角色列表
	@RequestMapping("/getRolesByUser")
	public List<Role> getRolesByUser(HttpServletRequest request, @RequestBody Role role){
		User user = new User();
		user.setUserId(request.getParameter("userId")==null?0:Integer.parseInt(request.getParameter("userId").toString()));
		return managerService.getRolesByUser(role, user);
	}
	// 给用户赋予权限
	@RequestMapping("/setUserFunction")
	public Map<String, Object> setUserFunction(HttpServletRequest request){
		String userId = request.getParameter("userId")==null?"0":request.getParameter("userId");
		String funArray = request.getParameter("funArray")==null?"":request.getParameter("funArray");
		return managerService.setUserFunction(Integer.parseInt(userId), funArray);
	}
	// 给用户赋予角色
	@RequestMapping("/setUserRole")
	public Map<String, Object> setUserRole(HttpServletRequest request){
		String userId = request.getParameter("userId")==null?"0":request.getParameter("userId");
		String funArray = request.getParameter("funArray")==null?"":request.getParameter("funArray");
		return managerService.setUserRole(Integer.parseInt(userId), funArray);
	}
	// 根据权限ID，获取权限记录
	@RequestMapping("/getFunction")
	public Function getFunction(@RequestBody Function fun){
		return managerService.getFunctionById(fun);
	}

}
